#include "downfile.h"

downfile::downfile(QObject *parent) : QObject(parent)
{

   networkAccessManager = new QNetworkAccessManager(this);

   if(QSysInfo::buildCpuArchitecture() == "arm"){
       DownFile = new QFile(this->ARMAddr);
   }else{
       DownFile = new QFile(this->UbantuAddr);
   }

}

QString downfile::GetTTSFile(QString tpye)
{
    if(tpye == "arm"){
        return this->ARMAddr;
    }else{
        return this->UbantuAddr;
    }
}

void downfile::readyReadData()
{
    /* 获取信号发送者 */
    QNetworkReply *reply = (QNetworkReply *)sender();

    /* 下载文件 */
    DownFile->write(reply->readAll());
}

void downfile::replyFinished()
{
    /* 获取信号发送者 */
    QNetworkReply *reply = (QNetworkReply *)sender();

    DownFile->close();
    reply->deleteLater();
    reply = NULL;
}

void downfile::startDownload(QString url)
{
    /* 网络请求 */
    QNetworkRequest  networkRequest;
    /* 设置下载的地址 */
    networkRequest.setUrl(QUrl(url));
    QSslConfiguration config;
    config.setPeerVerifyMode(QSslSocket::VerifyNone);
    config.setProtocol(QSsl::TlsV1SslV3);
    networkRequest.setSslConfiguration(config);
    /* 网络响应 */
    QNetworkReply *newReply = networkAccessManager->get(networkRequest);
     qDebug()<< QString(url) <<endl;
    if(!DownFile->open(QIODevice::WriteOnly))
        qDebug()<< "write error" <<endl;

    connect(newReply, SIGNAL(finished()),
            this, SLOT(replyFinished()));
    connect(newReply, SIGNAL(readyRead()),
            this, SLOT(readyReadData()));
    connect(newReply, SIGNAL(downloadProgress(qint64, qint64)),this,SLOT(downfileflag(qint64, qint64)));
}

void downfile::downfileflag(qint64 bytes, qint64 totalBytes)
{
   qDebug()<< bytes <<endl;
   qDebug()<< totalBytes <<endl;
    if(bytes == totalBytes){
        qDebug() << "Car_TTS_File Down ok!"  << endl;
   }
}

